import utils from '../../../utils/index'

const gameAll = function() {
    console.log('gamealll')
    var size = {width:window.innerWidth,height:window.innerHeight};
    var gameIns = window.game || new Phaser.Game(size.width * 2, size.height * 2, Phaser.AUTO, 'phaser');
    console.log(gameIns)
    if(window.game){
        document.getElementById('phaser').appendChild(window.game.canvas);
    }else{
        window.game = gameIns;
    
    }
   
    gameIns.transparent = true;
    var start = false;
    var states = {};
    //全局组，包括robot，各种阶梯，装饰
    var groupItem;
    //阻碍阶梯组
    var stoneFlagGroup;
    //树叶组
    var scenes;
    var sceneNum = 1;
    //普通阶梯组
    var stones;
    //无阻碍台阶数组
    var stoneArr = [];

    // 方向
    var defaultDirection = 1;
    // 第一个格子的坐标
    var stone0X = 0;
    var stone0Y = 0;
    const stoneWidth = Number((window.innerWidth*0.44).toFixed(2))
    const stoneHeight = Number((window.innerWidth*0.44*0.93).toFixed(2))
    const intervalX = stoneWidth*0.5
    const intervalY = intervalX/1.5
    // 当前步数
    var currentStep = 0;

    //机器人
    var robotGroup;
    var robot;
    var avator;
    //机器人坐标记录
    var robotX;
    var robotY;
    let bgMusic
    var  stonesGroup = [];
    var stoneStopAddition = [];

    var inUtils = {
        getPathName:function(){
            var pn = window.location.pathname;
            var pnArr = pn.split('/');
            var newArr = [];
            for(var i=0;i<pnArr.length;i++){
                if(pnArr[i] && pnArr[i].indexOf('html') == -1){
                    newArr.push(pnArr[i]);
                }
            }
            return newArr.length > 0 ? '/' + newArr.join('/') : '';
        }
    }

    states.load = {
        preload: function() {
            gameIns.scale.pageAlignHorizontally = true;
            gameIns.scale.pageAlignVertically = true;
            // gameIns.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            gameIns.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            // gameIns.scale.aspectRatio = 16/9; // 设置所需的宽高比
            // gameIns.scale.refresh()
            var path = inUtils.getPathName();
            var ossPath = import.meta.env.VITE_ASSETS_IMAGE_URL;
            // gameIns.load.image('gameBg', path+ '/images/game-bg.png')
            // gameIns.load.image('stone0', ossPath + '/images/stone0.png');
            // gameIns.load.image('scene1', ossPath + '/images/scene1.png');
            // gameIns.load.image('scene2', ossPath + '/images/scene2.png');
            // gameIns.load.image('scene3', ossPath + '/images/scene3.png');
            // gameIns.load.image('scene4', ossPath + '/images/scene4.png');
            // gameIns.load.image('scene5', ossPath + '/images/scene5.png');
            // gameIns.load.image('scene6', ossPath + '/images/scene6.png');
            // gameIns.load.image('scene7', ossPath + '/images/scene7.png');
            // gameIns.load.image('scene8', ossPath + '/images/scene8.png');
            // gameIns.load.image('scene9', ossPath + '/images/scene9.png');
            // gameIns.load.image('scene10', ossPath + '/images/scene10.png');
            // gameIns.load.image('scene11', ossPath + '/images/scene11.png');
            gameIns.load.image('stone', ossPath + '/images/stone.png');
            gameIns.load.atlas('spritestairs', import.meta.env.VITE_ASSETS_IMAGE_URL + '/images/spritestairs.png', import.meta.env.VITE_ASSETS_IMAGE_URL + '/images/spritestairs.json');
            gameIns.load.image('robot', import.meta.env.VITE_ASSETS_IMAGE_URL + '/images/robot.png');
            gameIns.load.image('prize-bg', import.meta.env.VITE_ASSETS_IMAGE_URL+'/images/topb-icon.png')
            gameIns.load.image('topb-icon', import.meta.env.VITE_ASSETS_IMAGE_URL+'/images/topb.png')
            gameIns.load.image('shiwu-icon', import.meta.env.VITE_ASSETS_IMAGE_URL+'/images/shiwu-icon.png')
            // gameIns.load.audio('bgMusic', import.meta.env.VITE_ASSETS_IMAGE_URL+'/audio/clearday.mp3')
            gameIns.load.crossOrigin = 'anonymous'
            try {
                const userInfo = utils.getUserInfo();
                if(userInfo.avatar) {
                    gameIns.load.image('avator', userInfo.avatar)
                }
                
            } catch(e) {
                gameIns.load.image('avator', import.meta.env.VITE_ASSETS_IMAGE_URL + '/images/avator.jpg');
            }
            // gameIns.load.image('avator', import.meta.env.VITE_ASSETS_IMAGE_URL + '/images/22311692805304_.pic.jpg');     

            gameIns.load.onFileComplete.add(function(progress) {
                document.querySelector('.curr_process').style.width = progress + '%';

                if(progress == 100){
                    setTimeout(function(){
                        window.dispatchEvent(new CustomEvent('progress'));
                        //  bgMusic = gameIns.add.audio('bgMusic')
                        //  bgMusic.loop = true
                        // bgMusic.play()
                    },500);
                    
                    gameIns.state.start('play');

                }
            });
        }
    }


    states.play = {
        create: function() {
            create();
        },
    }

    function create() {
        
        console.log(gameIns)
        console.log()
        // const bg = gameIns.add.image(0,0, 'gameBg')
        // bg.width = game.width
        // bg.height = game.height
        //创建第一个格子
        stoneCreateFirst();

        // 创建首屏格子
        stoneCreate(14);

        //创建机器人
        robotCreate();

        //创建两边的建筑物和树
        // sceneCreate();
    }

    function reset(){
        console.log("=====================");
        stoneArr = [];
        stoneStopArr = [];
        stoneStopFlagArr = [];
        stoneAdditionArr = [];
        text_length = 0
        textIndex = 0;
        start = false;
        over = false;
        currentPos = 0;
        score = 0;
        dropStoneTime = 800;
        window.dispatchEvent(new CustomEvent('score',{detail:{score:0}}));
        window.dispatchEvent(new CustomEvent('extraPoints',{detail:{index:-1}}));
        document.querySelector('.score').innerHTML = 0;
    }

    //创建机器人
    function robotCreate() {

        
        // robot = gameIns.add.sprite(0, 0, 'robot');
        robot = robotGroup.create(0, 0, 'robot');
        robot.scale.setTo(0.5)
        robotGroup.x = stone0X + robot.width/2-4;
        robotGroup.y = stone0Y -robot.height/2+10;
        // robotX = robot.x = stone0X - 70 + 100;
        // robotY = robot.y = stone0Y - 100;

        // avator = gameIns.add.sprite(0, 0, 'avator');
       

        robotGroup.addChild(robot);
        
        if (gameIns.cache.checkImageKey('avator')) {
            avator = robotGroup.create(30, 30, 'avator');
            avator.anchor.setTo(0.5);
            avator.x = robot.width/2
            avator.y = robot.height/2-12
            const scale = 112 / (avator.width > avator.height ? avator.height : avator.width);
            avator.scale.setTo(scale.toFixed(2));
            // console.log(avator.x)
            
            // 绘制圆形,作为头像的遮罩
            let circle = gameIns.add.graphics(30, 30);
            circle.beginFill(0x0000);
            circle.drawCircle(0, robot.height*0.18, robot.width-28);
            circle.x = robot.width/2
            circle.y = robot.height*0.25
            // let mask = gameIns.add.tileSprite(avator.x, avator.y, avator.width, avator.height);
            // mask.drawCircle(avator.width/2, avator.height/2, avator.width/2); 
            
            // // 设置遮罩
            avator.mask = circle;
            // circle.x = robot.x
            // circle.y = 10
            robotGroup.addChild(circle);
            robotGroup.addChild(avator);
        }
        
        groupItem.addChild(robotGroup);
    }
    this.playBgAudio = function(value) {
        // console.log(value,'value')
        // if (value) {
        //     return bgMusic.play()
        // }
        // bgMusic.stop()
        
    }
    // 根据投掷的骰子点数移动到指定格子上
    this.spriteMove = function(num, category, cb) {
        let n = 0;
        // robotGroup.animations.add('move', [0,1,2,3,4,5,6,7,8,9], 60, true);

        function animation() {
            if (n >= num) {
                //画面移动
                // gameIns.add.tween(groupItem).to( { y: groupItem.y + num * 57/2 }, 100, Phaser.Easing.Linear.None).start();
                // const first3 = stoneArr.slice(0,2)
                // first3.forEach((item) => {
                //     item.destroy()
                // })
                // // gameIns.renderer.renderSession.contextLost()
                // console.log(gameIns)
                // // 创建投掷骰子点数的格子
                // stoneCreate(num);
                
                // 创建奖励
                flagCreate(category);
                setTimeout(() => {
                    // sceneCreate(3);
                
                // console.log(stoneArr.length)
                // 到达20格以后，剩余格子不够最大6点，游戏回到起点
                if (currentStep >= 20) {
                    // console.log('到达20,重置游戏')
                    robotGroup.x = stone0X +50;
            robotGroup.y = stone0Y -55;
            currentStep=0
                }
                    cb && cb();
                }, 300)
                return;
            }

            // 播放动画
            // robotGroup.animations.play('move');

            let x = stoneArr[currentStep].x +robot.width/2-4;
            let y = stoneArr[currentStep].y - robot.height/2+10;
            let tween = gameIns.add.tween(robotGroup);

            tween.to({ x, y }, 220, Phaser.Easing.Linear.None);
            tween.onComplete.add(function() {
                n++;
                currentStep++;
                animation();
            })
            
            tween.start();
        }

        animation();
        
    }

    // 创建两边的建筑物和树
    function sceneCreate() {
        let isAdd = false;
        let scene1 = game.add.image(stone0X-400 , stone0Y-120 , 'scene1');
        let scene6 = game.add.image(stone0X, stone0Y + 130, 'scene4');
        
        scenes.addChild(scene6);
        let scene3 = game.add.image(stoneArr[ sceneNum * 6].x - 400, stoneArr[sceneNum * 6].y-120, 'scene3');
            
        let scene2 = game.add.image(stone0X-320,stone0Y+50, 'scene2');
            
            // let scene4 = game.add.image(stoneArr[ sceneNum * 6 - 3].x - 50, stoneArr[sceneNum * 6 - 3].y + 40, 'scene4');
            
            let scene5 = game.add.image(stoneArr[ sceneNum * 6 - 5].x - 150, stoneArr[sceneNum * 6 - 5].y - 560, 'scene4');
            scenes.addChild(scene5);
            let scene7 = game.add.image(stoneArr[ sceneNum * 6 - 5].x -280, stoneArr[sceneNum * 6 - 5].y + 40, 'scene5');
            let scene8 = game.add.image(stoneArr[ sceneNum * 6 - 5].x +160, stoneArr[sceneNum * 6 - 5].y-160 , 'scene6');
            let scene9 = game.add.image(stoneArr[ sceneNum * 6 - 5].x +260, stoneArr[sceneNum * 6 - 5].y-360 , 'scene7');
            let scene10 = game.add.image(stoneArr[ sceneNum * 6 - 5].x +190, stoneArr[sceneNum * 6 - 5].y-550 , 'scene8');
            let scene11 = game.add.image(stoneArr[ sceneNum * 6 - 5].x-48 , stoneArr[sceneNum * 6 - 5].y-700 , 'scene9');
            let scene12 = game.add.image(stoneArr[ sceneNum * 6 - 5].x +80, stoneArr[sceneNum * 6 - 5].y-460 , 'scene10');
            let scene13 = game.add.image(stoneArr[ sceneNum * 6 - 5].x -40, stoneArr[sceneNum * 6 - 5].y+100 , 'scene11');
            scene10.angle = 2
            scene11.angle = 3
            scenes.addChild(scene7);
            // scenes.addChild(scene4);
            scenes.addChild(scene3);
            scenes.addChild(scene1);
            scenes.addChild(scene2);
            scenes.addChild(scene8)
            
            scenes.addChild(scene10)
            scenes.addChild(scene9)
            scenes.addChild(scene11)
            scenes.addChild(scene12)
            scenes.addChild(scene13)
        // if (stoneArr[sceneNum * 6 + 6]) {
            
        //     isAdd = true;
        // } else {
        //     isAdd = false;
        // }
        // if (stoneArr[sceneNum * 6 + 3]) {
        //     // 下面的路
            
        // } else {
        //     isAdd = false;
        // }
        // if (stoneArr[sceneNum * 6]) {
            
        // } else {
        //     isAdd = false;
        // }
        // if (stoneArr[sceneNum * 6 - 3]) {
            
        // } else {
        //     isAdd = false;
        // }
        // if (stoneArr[sceneNum * 6 - 5]) {
           
        // } else {
        //     isAdd = false;
        // }
        
        // if (isAdd) {
        //     sceneNum += 2;
        // }
    }

    //第一颗台阶
    function stoneCreateFirst(){
        //普通阶梯组
        stonesGroup = gameIns.add.group();

        // 两边建筑物组
        scenes = gameIns.add.group();

        // 格子上图标
        stoneFlagGroup = gameIns.add.group();

        // 机器人组
        robotGroup = gameIns.add.group();

        // 加成组

        stoneStopAddition = gameIns.add.group();

        //全局组，包括robot，各种阶梯，装饰
        groupItem = gameIns.add.group();

        groupItem.addChild(stonesGroup);
        groupItem.addChild(stoneFlagGroup);
        groupItem.addChild(stoneStopAddition);
        // groupItem.addChild(scenes);

        var stone0 = gameIns.add.sprite(0, 0, 'stone');
        var stone1 = gameIns.add.sprite(0, 0, 'stone');
        // let stoneFlag = gameIns.add.sprite(0, 0, 'spritestairs', 'flag5.png')

        stone0.width = stoneWidth
        stone0.height = stoneWidth
        stone0X = stone0.x = gameIns.width - (stone0.width) - ((gameIns.width - stone0.width * 5 / 2));
        // stone1.y = gameIns.height / 2 +  stone1.height;
        // stone1.x = stone1Pos.x;
        stone0Y = stone0.y = gameIns.height * 0.62;
        stone1.width = stoneWidth
        stone1.height = stoneWidth
        stone1.x = stone0.x - intervalX-6;
        stone1.y = stone0.y - intervalY-3;
        // stoneFlag.x = stone1.x + 68;
        // stoneFlag.y = stone1.y + 38;
        // stone1.y = gameIns.height 

        stonesGroup.addChild(stone0);
        // stonesGroup.setChildIndex(stone0,0)
        stonesGroup.addChild(stone1);
        stonesGroup.setChildIndex(stone1, 0);
        // stoneFlagGroup.addChild(stoneFlag);
        stoneArr.push(stone1);
    }
    function stoneCreate1(i,defaultDirection) {
        let stonePos = {
            x: 0,
            y: 0
        };
        let stoneFlagPos = {
            x: 0,
            y: 0
        };
        // if (i === 8||i === 2||i === 4||i ===6||i==3) {
        //     defaultDirection = -1
        // } else {
        //     defaultDirection = 1
        // }
        // 每三格转换一下方向
        
        // defaultDirection = (stoneArr.length - 1) % 2 === 0 ? defaultDirection * -1 : defaultDirection
        // if ([4,9,13].includes(i)) {
        //     defaultDirection = -1
        // }
// debugger
        if (defaultDirection === -1) {
            stonePos = {
                x: stoneArr[stoneArr.length - 1].x+intervalX,
                y: stoneArr[stoneArr.length - 1].y - intervalY
            };
        } else  {
            stonePos = {
                x: parseFloat((stoneArr[stoneArr.length - 1].x-intervalX).toFixed(2)),
                y: stoneArr[stoneArr.length - 1].y - intervalY
            };
            console.log(stonePos)
        }
        if (i === 3||i === 9) {
            stonePos = {
                x: stoneArr[stoneArr.length - 1].x+intervalX,
                y: stoneArr[stoneArr.length - 1].y +intervalY
            }
        }
        if (i === 6) {
            stonePos = {
                x: stoneArr[stoneArr.length - 1].x -intervalX,
                y: stoneArr[stoneArr.length - 1].y + intervalY
            }
        }
        // if (i === 9) {
        //     console.log(999999)
        //     stonePos = {
        //         x: stoneArr[stoneArr.length - 1].x +intervalX,
        //         y: stoneArr[stoneArr.length - 1].y + intervalY
        //     }
        // }
        stoneFlagPos = {
            x: stonePos.x + intervalX,
            y: stonePos.y + intervalY
        }

        let stone = gameIns.add.sprite(stonePos.x, stonePos.y, 'stone');
        // let stoneFlag = gameIns.add.sprite(stoneFlagPos.x, stoneFlagPos.y, 'spritestairs', 'flag5.png');

        stone.alpha = 0;
        let fadeIn = game.add.tween(stone).to({alpha: 1}, 600, Phaser.Easing.Linear.None);

        fadeIn.start();

        // stoneFlag.alpha = 0;
        // let fadeIn1 = game.add.tween(stoneFlag).to({alpha: 1}, 800, Phaser.Easing.Linear.None);

        // fadeIn1.start();
        stone.width = stoneWidth
        stone.height = stoneHeight
        stonesGroup.addChild(stone);
        stonesGroup.setChildIndex(stone, i === 3||i===6||i===9? stoneArr.length+1:0);
        // stoneFlagGroup.addChild(stoneFlag);
        stoneArr.push(stone);
    }
    //创建首屏格子
    function stoneCreate(num) {
        for(let i = 0;i<1;i++) {
            stoneCreate1(1,1)
        }
        for(let i = 0; i<3;i++) {
            stoneCreate1(2,-1)
        }
        for(let i = 0; i<1;i++) {
            stoneCreate1(3,1)
        }
        for(let i = 0; i<2;i++) {
            stoneCreate1(4,-1)
        }
        for(let i = 0; i<3;i++) {
            stoneCreate1(5,1)
        }
        for(let i = 0; i<2;i++) {
            stoneCreate1(6,-1)
        }
        for(let i = 0; i<2;i++) {
            stoneCreate1(7,1)
        }
        for(let i = 0; i<4;i++) {
            stoneCreate1(8,-1)
        }
        for(let i = 0; i<2;i++) {
            stoneCreate1(9,1)
        }
        for(let i = 0; i<2;i++) {
            stoneCreate1(10,-1)
        }
        for(let i = 0; i<3;i++) {
            stoneCreate1(11,1)
        }
    }

    // 创建奖励精灵
    function flagCreate(num = 4) {
        // if (num < 1 || num > 4) return;
        let index = currentStep - 1;
        const flagGroup = gameIns.add.group()
        flagGroup.create(0,0,'prize-bg')
        flagGroup.width = stoneWidth*1.3
        flagGroup.height = stoneHeight *1.3
        flagGroup.x = stoneArr[index].x - stoneWidth*0.24;
        flagGroup.y = stoneArr[index].y - stoneHeight*0.68;
        if (num === 3) {
            const topb = gameIns.add.sprite(flagGroup.width/2,flagGroup.height,'topb-icon')
            topb.x = flagGroup.width/2+ topb.width/2+30
            flagGroup.addChild(topb)
        } else {
            const shiwu = gameIns.add.sprite(flagGroup.width/2,flagGroup.height,'shiwu-icon')
            shiwu.x = flagGroup.width/2+shiwu.width-18
            flagGroup.addChild(shiwu)
        }
        let flag
        return
        console.log(num)
        // if (num === 1) {
        //     flag = gameIns.add.sprite(0, 0, 'shiwu-icon');
        //     // flag1
        //     flag.x = stoneArr[index].x + stoneWidth/2;
        //     flag.y = stoneArr[index].y - stoneHeight/2;
        // } else if (num === 2) {
        //     flag = gameIns.add.sprite(0, 0, 'shiwu-icon');
        //     // flag2
        //     flag.x = stoneArr[index].x + 40 + 18;
        //     flag.y = stoneArr[index].y + 10;
        // } else 
        if (num === 3) {
            flag = gameIns.add.sprite(0,0,'topb-icon')
            
            // flag3
            
        } else {
            // flag4
            flag = gameIns.add.sprite(0, 0, 'shiwu-icon');
            flag.x = stoneArr[index].x + stoneWidth/2;
            flag.y = stoneArr[index].y - stoneHeight/2;
        }
        flag.width = stoneWidth*1.3
            flag.height = stoneHeight *1.3
        flag.x = stoneArr[index].x - stoneWidth*0.24;
            flag.y = stoneArr[index].y - stoneHeight*0.68;
        let oldFlag = stoneFlagGroup.getAt(index);
        stoneFlagGroup.replace(oldFlag, flag);
    }

    this.init = function() {
        console.log(gameIns.state)
        gameIns.state?.add('load', states.load);
        gameIns.state?.add('play', states.play);
        gameIns.state?.start('load');
    }
    // init()
    this.destroy = function() {
//         bgMusic.pause()
//         // gameIns.destroy()
//             bgMusic.currentTime = 0
//         bgMusic.destroy(bgMusic)
//         gameIns.world.removeAll();
// gameIns.time.removeAll();

        
    }
    window.addEventListener("game_reset",()=>{
        reset()

        game.state.start('play');
    })
}

export default gameAll





